"""
Author: Jian SuiYue kaohx0214@yeah.net
Date: 2025-05-20 15:30:00
LastEditTime: 2025-05-15 17:09:14
FilePath: LibraryManagerStudio/web/routes/log_api.py
"""
from typing import Optional

from fastapi import APIRouter, HTTPException, Query, status
from fastapi.responses import JSONResponse

from .token_api import validate_jwt
from ...database import get_logs, get_available_log_dates
from ...datamodel import LogResponse, LogDatesResponse

# 创建日志路由
router = APIRouter()


@router.get("/query", response_model=LogResponse)
async def query_logs(
        login: str = Query(...),
        year: Optional[int] = Query(None, description="年份"),
        month: Optional[int] = Query(None, description="月份"),
        day: Optional[int] = Query(None, description="日期"),
        level: Optional[str] = Query(None, description="日志级别"),
        search: Optional[str] = Query(None, description="搜索文本"),
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(100, ge=1, le=1000, description="每页条数"),
):
    """
    查询日志，支持按年月日、日志级别和文本过滤
    仅管理员可访问
    """
    validate_jwt(login)

    result = get_logs(
        year=year,
        month=month,
        day=day,
        level=level,
        search_text=search,
        page=page,
        page_size=page_size
    )

    if "error" in result:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=result["error"])

    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": result, "message": "query logs successful"}
    )


@router.get("/dates", response_model=LogDatesResponse)
async def get_log_dates(login: str = Query(...)):
    """
    获取可用的日志日期列表
    仅管理员可访问
    """
    validate_jwt(login)
    dates = get_available_log_dates()
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": dates, "message": "get log dates successful"}
    )
